package kam.fire;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
/** The LoginController handles all logic associated with the login screen.
* this includes all text fields and login buttons.
*
* @author Derek Kam
* 
*/
public class LoginController extends Activity {
	/**
	 *holds a user info to be uses and written to database
	 */
	User user = new User();
	/**
	 *gives access to read and write to theSQLite database
	 */
	DatabaseHelper db = DatabaseHelper.getHelper(this);
	/**
	 *used to hold the user's options settings retrieved and written to database
	 */
	Options options = new Options();
	
	/**holds the users "password" and is read from the editText box or read from 
	 * database if option is set to remember it
	 */
	private String apiToken;
	
	/** The private kamfire instance is used to handle all HTTP connections to Campfire as well as some 
	 * utilities such as gif rendering.*/
	private KamfireInstance kamfire;
	
	/**
	 * calls checkOptions()
	 */
	@Override
	protected void onResume() {
		super.onResume();
		checkOptions();
	}
	/**
	 * calls checkOptions
	 */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		//db.recreateTables();
		checkOptions();
		// check last user options to check or uncheck boxes
		
		
	}
	
	
	/**
	 * 
	 *retrieves text from editTextFields (campsite,apiToken), calls attemptLogin(String,String)
	 * 
	 * @param v			v is the button pressed.
	 * @return			void
	 */
	public void login(View v) {

		TextView siteField;
		siteField = (TextView) findViewById(R.id.SiteField);
		TextView apiField;
		apiField = (TextView) findViewById(R.id.ApiField);

		apiToken = apiField.getText().toString().trim();
		 ConnectivityManager connMgr = (ConnectivityManager) 
		            getSystemService(Context.CONNECTIVITY_SERVICE);
		        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
		        if (networkInfo != null && networkInfo.isConnected()) {
		        	attemptLogin(siteField.getText().toString().trim(), apiToken);
		        } else {
		            noConnection();
		        }
		

	}
	/**
	 *  calls kamfireInstance.login(site,token). 
	 * Depending on the result of that it will either call userInfor(User) and loginSucess() or loginFail();
	 * 
	 * @param site
	 * @param token
	 */
	private void attemptLogin(String site, String token) {
		kamfire = new KamfireInstance(site, token);
		boolean success = kamfire.login();
		if (success)
		{
			userInfo(kamfire.getUser());
			loginSucess();
		}
		else
		{
			loginFail();
		}

	}
	
	/**
	 * reads the last user's options from the database and updates the 
	 * campsite editText, apiToken editText, saveCapsite check box, and saveToken check box accordingly. 
	 */
	private void checkOptions() {
		options = db.getOptions();
		user = db.getUserByIndex(options.getUserIndex());

		if (options.getCampsiteBox()) {
			CheckBox siteBox = (CheckBox) findViewById(R.id.rememberSiteBox);
			siteBox.setChecked(options.getCampsiteBox());
			EditText siteField = (EditText) findViewById(R.id.SiteField);
			siteField.setText(user.getCampsite());
		}
		if (options.getTokenBox()) {
			CheckBox tokenBox = (CheckBox) findViewById(R.id.rememberApiBox);
			EditText tokenField = (EditText) findViewById(R.id.ApiField);
			tokenBox.setChecked(options.getTokenBox());
			tokenField.setText(user.getApiAuthToken());
		}
	}

	/**
	 * updates options info with what is on screen. overwrites the user object from 
	 * database with user object from campfire and sets or erases campsite and or api token fields 
	 * according to options. calls addUserToDB and addOptionsToDB
	 * @param u
	 */
	private void userInfo(User u) {

		CheckBox siteBox = (CheckBox) findViewById(R.id.rememberSiteBox);
		CheckBox tokenBox = (CheckBox) findViewById(R.id.rememberApiBox);

		user = u;

		if (siteBox.isChecked()) {
			EditText siteField = (EditText) findViewById(R.id.SiteField);
			user.setCampsite(siteField.getText().toString());
		} else {
			user.setCampsite("");
		}

		if (tokenBox.isChecked()) {
			EditText apiField = (EditText) findViewById(R.id.ApiField);
			user.setApiAuthToken(apiField.getText().toString());
		} else {
			user.setApiAuthToken("");
		}

		addUserToDB();
		options.setCampsiteBox(siteBox.isChecked());
		options.setTokenBox(tokenBox.isChecked());
		options.setUserIndex(user.getUserIndex());
		options.setUserId(user.getId());

		addOptionsToDB();

	}

	/**
	 * saves global variable user to database
	 * calls db.addUser(User)
	 */
	private void addUserToDB(){
		db.addUser(user); // addUser uses db.replace
	}

	/**
	 * 
	 * adds global variable options to database
	 * calls db.addOptions(Options) 
	 */
	private void addOptionsToDB(){
		db.addOptions(options);	
	}
	
	/**
	 * creates bundle with USER_INDEX, USER_CAMPSITE, USER_APITOKEN
	 * changes intent to roomsController passes userBundle
	 */
	private void loginSucess() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setClassName(this, RoomsController.class.getName());
		Bundle userBundle = new Bundle();

		userBundle.putSerializable("USER_INDEX", user.getUserIndex());
		userBundle.putSerializable("USER_CAMPSITE", user.getCampsite());
		userBundle.putSerializable("USER_APITOKEN", apiToken);
		intent.putExtras(userBundle);

		this.startActivity(intent);
	}

	/**
	 *  creates a toast saying the login failed
	 */
	private void loginFail() {
		Toast toast = Toast.makeText(this, "Incorrect Username or Password",
				Toast.LENGTH_SHORT);
		toast.show();
	}

	/**
	 * creates a toast saying there is no connection to Internet
	 */
	private void noConnection() {
		Toast toast = Toast.makeText(this, "No Internet Service",
				Toast.LENGTH_SHORT);
		toast.show();
	}
}